<template>
  <view class="container">
    <!-- 头像显示区域（移除上传功能）-->
    <view class="avatar-section">
      <image class="avatar" :src="defaultAvatar"></image>
    </view>

    <!-- 资料编辑表单 -->
    <view class="form-section">
      <view class="form-item">
        <text class="label">用户名</text>
        <input class="input" v-model="form.username" placeholder="请输入用户名" />
      </view>
      <view class="form-item">
        <text class="label">性别</text>
        <picker @change="bindGenderChange" :value="genderIndex" :range="genders">
          <view class="picker">{{ form.gender || '请选择性别' }}</view>
        </picker>
      </view>
      <view class="form-item">
        <text class="label">出生日期</text>
        <picker mode="date" @change="bindDateChange">
          <view class="picker">{{ form.birthDate || '请选择出生日期' }}</view>
        </picker>
      </view>
    </view>

    <!-- 提交按钮 -->
    <button class="submit-btn" @click="submitForm">保存修改</button>
  </view>
</template>

<script>
import api from '@/api/index.js';
export default {
  data() {
    return {
      genders: ['男', '女'],
      genderIndex: 0,
      defaultAvatar: 'https://q2.itc.cn/q_70/images03/20250225/e8117dd40aae4db5a64461f1ea0d16fc.jpeg', // 默认头像路径
      form: {
        username: '',
        gender: '',
        birthDate: '', // 使用新字段 birthDate
      }
    }
  },
  onShow() {
    this.loadUserInfo();
  },
  methods: {
    // 加载用户信息，但不加载avatar
    loadUserInfo() {
      const userInfo = uni.getStorageSync('userInfo') || {};
      this.form = {
        username: userInfo.username || userInfo.name || '', // 从 username 或 name 中获取值
        gender: userInfo.gender || '',
        birthDate: userInfo.birthDate || userInfo.birthday || '' // 从 birthDate 或 birthday 中获取值
      };
    },

    // 性别选择
    bindGenderChange(e) {
      this.genderIndex = e.detail.value;
      this.form.gender = this.genders[e.detail.value];
    },

    // 日期选择
    bindDateChange(e) {
      this.form.birthDate = e.detail.value;
    },

    // 提交表单
    submitForm() {
      if (!this.form.username) {
        uni.showToast({ title: '用户名不能为空', icon: 'none' });
        return;
      }
    
      // 显示加载提示
      uni.showLoading({ title: '保存中...' });
    
      try {
        // 先获取本地存储中现有的userInfo，保留原有信息
      const currentUserInfo = uni.getStorageSync('userInfo') || {};
      
      // 构建更新的数据结构，保留原有信息，只更新修改的字段
      const updatedInfo = {
        ...currentUserInfo, // 扩展现有信息
        username: this.form.username, // 更新或添加用户名
        gender: this.form.gender, // 更新或添加性别
        birthDate: this.form.birthDate // 更新或添加出生日期
      };
      
      // 调用后端API更新用户信息
      api.updateUserInfoApi(updatedInfo).then(res => {
        if (res.code === 200) {
          // 后端更新成功后，更新本地存储
          uni.setStorageSync('userInfo', updatedInfo);
          
          uni.showToast({ title: '修改成功' });
          setTimeout(() => {
            uni.navigateBack();
          }, 1500);
        } else {
          // 后端更新失败
          uni.showToast({ title: res.message || '修改失败', icon: 'none' });
        }
      }).catch(err => {
        console.error('更新用户信息API调用失败:', err);
        // 如果API调用失败，保存到本地
        uni.setStorageSync('userInfo', updatedInfo);
        uni.showToast({ title: '已保存到本地，待网络恢复后自动同步', icon: 'none' });
        setTimeout(() => {
          uni.navigateBack();
        }, 1500);
      }).finally(() => {
        // 隐藏加载提示
        uni.hideLoading();
      });
      } catch (error) {
        console.error('保存用户信息失败:', error);
        uni.showToast({ title: '保存失败，请重试', icon: 'none' });
        uni.hideLoading();
      }
    }
  }
}
</script>

<style scoped>
.container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.avatar-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin: 20px 0;
}

.avatar {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  margin-bottom: 10px;
}

.avatar-text {
  color: #666;
  font-size: 14px;
}

.form-section {
  background-color: white;
  border-radius: 10px;
  padding: 0 15px;
}

.form-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 50px;
  border-bottom: 1px solid #eee;
}

.form-item:last-child {
  border-bottom: none;
}

.label {
  font-size: 16px;
  color: #333;
}

.input {
  flex: 1;
  text-align: right;
  padding-right: 10px;
}

.picker {
  color: #666;
}

.readonly {
  color: #999;
}

.submit-btn {
  margin-top: 30px;
  background-color: #1E88E5;
  color: white;
  border-radius: 25px;
}
</style>
